<?php

namespace app\admin\service;

use app\admin\model\Setting as SettingModel;

class SettingService
{
    protected $model;

    public function __construct(){
        $this->model = app()->make(SettingModel::class);
    }

    /**
     * 根据名字查询配置
     *
     * @param string $name
     * @return SettingModel|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function queryByName(string $name){
        return $this->model->where('name', $name)->find();
    }

    /**
     * @return SettingModel[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function queryList()
    {
        $list = $this->model->field('id, name, value, is_default, type')->select();
        return $list;
    }

    public function save(array $data): int
    {
        $result = null;
        if (empty($data['id'])) {
            $this->model->insert($data);
            return $this->model->getLastInsID();
        } else {
            $this->model->where('id', $data['id'])->save($data);
            return $data['id'];
        }
    }
}